<?php 
namespace Services;
use \Entity;
use \DbConnection;

/**
 * ????
 *
 * @copyright Copyright (c) 2013
 * @version   1.0
 * 
 * @todo commenter la classe
 **/
class AddAction
{	
	protected $_msg;
	
    /**
    * Constructor
    * 
    * @return void
    */    
    public function __construct () {
		$this->_msg = NULL;
    }
	
	/**
	* @todo Tester l'exitance et le type des données (colonnes) et convertir en fonction de ce type
	* @todo Ajouter le système de regles de gestion
	*/
	public function execute($serviceCtrl, $params) {
		$serviceCtrl->writeTrace('[Service\\AddAction] - execute de l\'action ADD');	
		$serviceCtrl->writeTrace('[Service\\AddAction] - entité =', $params['e']);	
		
		$serviceCtrl->writeTrace('[Service\\AddAction] - récupération du parametre fields');
		if (isset($params['fields'])) {
			$serviceCtrl->writeTrace('[Service\\AddAction] - fields :', $params['fields']);
			$fields = json_decode($params['fields']);
			//. TODO traiter les erreurs avec json_last_error()
		} else {
			$serviceCtrl->writeTrace('[Service\\AddAction] - parametre fields absent');
			$this->_msg = 'paramètre fields absent';
		}
		
		$serviceCtrl->writeTrace('[Service\\AddAction] - recherche de l\'entité avec le code ', $params['e']);
		
		$e = new Entity();
		if (!$e->ead($params['e'])){
			$this->_msg = 'entité inconnue - vérifier le code ' . $params['e'];
			return NULL;
		}
		
		$tableName = $e->bddTable;
		$serviceCtrl->writeTrace('[Service\\AddAction] - Nom de la table : ', $tableName);
		
		$objectid = $e->CreateSysObject($serviceCtrl->getUserMembership()->getUserId());
		$serviceCtrl->writeTrace('[Service\\AddAction] - Object_id: ', $objectid);
		
		$query = 'insert into ' . $tableName . ' (object_id';		
		$valPlaceHolder = ') values (<n:object_id/>';
		$values = array( 'n:object_id' => $objectid);
		
		foreach($fields as $key => $val) {
			$colName = mysql_real_escape_string($key);
			$query .= ', ' . $colName;
			$paramName = 's:' . $colName;
			$valPlaceHolder .= ', <' . $paramName . '/>';
			$values[$paramName] = $val;
		}
		
		$query .= $valPlaceHolder .')';

		$serviceCtrl->writeTrace('[Service\\AddAction] - Requete : ', $query);
				
		DbConnection::getInstance()->Execute($query, $values);
		
		$id = DbConnection::getInstance()->getInsertId();		
		
		return array('id'=>$id);
	}	
	

} // END class